#include "comm.h"

int main()
{
    // 创建命名管道
    umask(0);
    if (mkfifo(FILE_NAME, 0666) < 0)
    {
        perror("mkfifo");
        return 1;
    }
    int fd = open(FILE_NAME, O_RDONLY);
    if (fd < 0)
    {
        perror("open");
        return 2;
    }
    char buff[128];
    while (1)
    {
        buff[0] = '\0';
        ssize_t msg = read(fd, buff, sizeof(buff)-1);
        if (msg > 0)
        {
            buff[msg] = '\0';
            printf("clint# %s\n",buff);
            char* lable = "+-*/%";
            char* p = buff;
            int flag = 0;
            while(*p)
            {
                switch(*p)
                {
                    case '+':
                        flag = 0;
                        break;
                    case '-':
                        flag = 1;
                        break;
                    case '*':
                        flag = 2;
                        break;
                    case '/':
                        flag = 3;
                        break;
                    case '%':
                        flag = 4;
                        break;
                }
                p++;
            }
            //分割字符
            char* data1 = strtok(buff,"+-*/%");
            char* data2 = strtok(NULL,"+-*/%");
            int num1 = atoi(data1);
            int num2 = atoi(data2);
            int ret = 0;
            switch(flag)
            {
                case 0:
                    ret = num1 + num2;
                    break;
                case 1:
                    ret = num1 - num2;
                    break;
                case 2:
                    ret = num1 * num2;
                    break;
                case 3:
                    ret = num1 / num2;
                    break;
                case 4:
                    ret = num1 % num2;
                    break;
            }
            printf("%d %c %d = %d\n",num1,lable[flag],num2,ret);
        }
        else if(msg == 0)
        {
            printf("clint quit!\n");
            break;
        }
        else
        {
            perror("read");
            break;
        }
    }
    close(fd);
    return 0;
}